package visual_db

import (
	"fmt"
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"io/ioutil"
	"net/http"
	"strconv"
)

func init() {
	server.Get("/api/Cgs/Portal/db/list", listDb, "数据源列表", server.Login)
	server.Get("/api/Cgs/Portal/db/detail", detailDb, "数据源详情", server.Login)
	server.Post("/api/Cgs/Portal/db/submit", saveDb, "添加数据源", server.Login)
	server.Post("/api/Cgs/Portal/db/update", updateDb, "更新数据源", server.Login)
	server.Post("/api/Cgs/Portal/db/remove", removeDb, "删除数据源", server.Login)
	server.Post("/api/Cgs/Portal/db/db-test", dbTest, "测试数据源连通性", server.Login)
}

func listDb(w http.ResponseWriter, r *http.Request) {
	// 分页
	current, err:= strconv.ParseInt(r.FormValue("current"), 10, 64)
	if err != nil {
		current = 0
	}
	size, err	:= strconv.ParseInt(r.FormValue("size"), 10, 64)
	if err != nil {
		size = 50
	}

	mdl := &Db{}
	duModel := base.GenerateDataUserModel(mdl, r)
	duModel.Page = &model.Page{
		Current: current,
		Size:    size,
	}
	visualService := NewDbService()
	res, err := visualService.List(duModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Get Successfully!").WithData(res))
}

func detailDb(w http.ResponseWriter, r *http.Request) {
	id, err := primitive.ObjectIDFromHex(r.FormValue("id"))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	dataUserModel := base.GenerateDataUserModel(&Db{Id: id}, r)
	dbService := NewDbService()
	res, err := dbService.GetOne(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Delete successfully!").WithData(res))
}

func saveDb(w http.ResponseWriter, r *http.Request) {
	visualMap := &Db{}
	err := helper.ReadRequestBody(visualMap, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	dataUserModel := base.GenerateDataUserModel(visualMap, r)
	dbService := NewDbService()
	err = dbService.Save(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Add successfully!").WithData(bson.M{"id": visualMap.Id}))
}

func updateDb(w http.ResponseWriter, r *http.Request) {
	visualMap := &Db{}
	err := helper.ReadRequestBody(visualMap, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	dataUserModel := base.GenerateDataUserModel(visualMap, r)
	dbService := NewDbService()
	err = dbService.Update(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Update successfully!").WithData(bson.M{"id": visualMap.Id}))
}

func removeDb(w http.ResponseWriter, r *http.Request) {
	// 根据id删除
	id, err := primitive.ObjectIDFromHex(r.FormValue("ids"))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	dataUserModel := base.GenerateDataUserModel(&Db{Id: id}, r)
	dbService := NewDbService()
	err = dbService.Remove(dataUserModel)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Delete successfully!"))
}

func dbTest(w http.ResponseWriter, r *http.Request) {
	//data := new(interface{})
	r.Body = http.MaxBytesReader(w, r.Body, int64(100<<20))
	s, err := ioutil.ReadAll(r.Body)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	fmt.Println(string(s))
	key := "zvyoNwC46QrVlhVDEtQkZ5BzBuUR7M09"
	decrypted := helper.DecryptWithKey(string(s), []byte(key))
	fmt.Println(decrypted)
	db := Db{}
	err = helper.FromJSON([]byte(decrypted), &db)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	err = helper.TestMySQL(db.Host, db.Port, db.Username, db.Password, db.Database)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK("Test connection successfully!"))
}
